#pragma once
#include <iostream>
#include "nocopy.hpp"
#include <string>
#include <cstdint> //uint16_t

#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <strings.h> //bzero

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"

static const std::string default_ip = "0.0.0.0"; //static 各个cpp文件中独立一份
static const uint16_t default_port = 8888;

static const int default_sockfd = -1;
class UdpServer : public nocopy 
{
public:
    UdpServer(const std::string& ip = default_ip, uint16_t port = default_port)
        :_ip(ip), _port(port), _sockfd(default_sockfd)
    {}
    void Init()
    {
        //1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)  //致命错误
        {
            lg.LogMessage(Fatal, "socket error, %d : %s\n", errno, strerror(errno));
            exit(sockfd_err);
        }
        lg.LogMessage(Info, "socket created, sockfd: %d\n", _sockfd);

        //2. 绑定
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_port = htons(_port);

        int ok = ::bind(_sockfd, (const struct sockaddr*)&local, sizeof local);
        if(ok == -1)
        {
            lg.LogMessage(Fatal, "bind error, %d : %s\n", errno, strerror(errno));
            exit(bind_err);
        }
    }
    void Start()
    {
        char buffer[1024];
        while(1)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int n = recvfrom(_sockfd, buffer, 1023, 0, (struct sockaddr*)&peer, &len);

            if(n > 0)
            {
                buffer[n] = 0;
                
                std::cout << InetAddr(peer).PrintDebug() << buffer << std::endl;
                sendto(_sockfd, buffer, 1024, 0, (const struct sockaddr*)&peer, len);
            }
        }
    }
    ~UdpServer()
    {}
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};
//如果是const修饰，而不是static const修饰，我觉得也是可以的，
// 在多个cpp文件链接时，即在const修饰的情况下，每个cpp文件中这个变量的地址一样，感觉也没什么问题